package lyh.hnu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import lyh.hnu.common.BaseContext;
import lyh.hnu.common.R;
import lyh.hnu.dto.DishDto;
import lyh.hnu.dto.OrdersDto;
import lyh.hnu.entity.po.Dish;
import lyh.hnu.entity.po.OrderDetail;
import lyh.hnu.entity.po.Orders;
import lyh.hnu.service.OrderDetailService;
import lyh.hnu.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        return orderService.submit(orders);
    }

    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(int page, int pageSize) {
        Page<Orders> pageinfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId())
                .orderByDesc(Orders::getOrderTime);
        Page<Orders> p = orderService.page(pageinfo, queryWrapper);

        Page<OrdersDto> ordersDtoPage = new Page<>();
        //对象拷贝
        BeanUtils.copyProperties(p, ordersDtoPage, "records");
        List<Orders> ordersRecords = p.getRecords();
        List<OrdersDto> ordersDtoRecords = ordersRecords.stream().map(item -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            String orderId = item.getNumber();
            List<OrderDetail> orderDetails = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderId).list();
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtoRecords);
        return R.success(ordersDtoPage);
    }
}
